#!/usr/bin/python3

from hiddev import HerosysHidDevice
from local import UdpClient
from protocal import DpmDataTrans

from common import *

from util.log import getLogger
logger = getLogger(10)

BUFFSIZE = BUFFER_SIZE - 12

class DpmLocalTrans(DpmDataTrans):
    def __init__(self):
        super().__init__()

        self.hid_io = HerosysHidDevice()
        self.tid_hid = None

    def on_assisted(self, addr):
        from threading import Thread

        print("已连接到协助方")
        self.addr_target = addr

        self.tid_hid = Thread(target=self.auto_send)
        self.tid_hid.start()

    def stop(self):
        self.isRunning = False

        logger.debug("释放HID设备")
        self.hid_io.destroy()
        if self.tid_hid:
            self.tid_hid.join()

    def auto_send(self):
        self.isRunning = True
        while self.isRunning:
            bytes_data = self.hid_io.read()
            if bytes_data is None:
                continue
            logger.debug(f"HID数据dai发送 >>> {len(bytes_data)}")
            # print("Recv HID data >> ", bytes_data[0:4])
            if bytes_data:
                while len(bytes_data) > BUFFSIZE:
                    self.send_data(bytes_data[:BUFFSIZE], self.addr_target)
                    logger.debug(f"HID数据发送 >>> {BUFFSIZE}")
                    bytes_data = bytes_data[BUFFSIZE:]
                self.send_data(bytes_data, self.addr_target)
                logger.debug(f"HID数据发送 >>> {len(bytes_data)}")


if __name__ == "__main__":
    # udp_network
    udp_client = UdpClient((BROKER_HOST, BROKER_PORT))
    protocal = DpmLocalTrans()
    udp_client.set_protocal(protocal)
    udp_client.start()

    protocal.register_assist("123456789")

    input("Input Anything to quit: ")

    print("即将回收线程...")
    udp_client.stop()
    udp_client.join()
    udp_client.destroy()
